package cn.tedu.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BeanFactory {
    private static Properties properties;
    //创建一个map集合充当bean容器
    private static Map<String,Object> beans;
    static {
        //实例化对象
        properties = new Properties();
        //读取配置文件
        InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");

        try {
            //加载配置文件
            properties.load(in);
            //初始化容器
            beans = new HashMap<String, Object>();
            //获取properties里的keys
            Enumeration<Object> keys = properties.keys();
            //遍历keys
            while (keys.hasMoreElements()){
                //取出每个key
                String key = keys.nextElement().toString();
                //根据key取出value
                String beanPath = properties.getProperty(key);
                //根据beanPath反射创建对象
                Object bean = Class.forName(beanPath).newInstance();
                //将bean和key放到容器Map
                beans.put(key,bean);
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化文件错误");
        }
    }

    public static Object getBean(String beanName){
        return beans.get(beanName);
    }

    /*public static Object getBean(String beanName){
        String beanPath = properties.getProperty(beanName);
        Object bean = null;
        try {
            bean = Class.forName(beanPath).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return bean;
    }*/
}
